<!DOCTYPE html>
<html lang="zh-cn">
    <head>
        <meta charset="utf-8">
        <title>浏览页面</title>
        <link rel="stylesheet" href="/app/admin/component/pear/css/pear.css" />
        <link rel="stylesheet" href="/app/admin/admin/css/reset.css" />
    </head>
    <body class="pear-container">
    
        <!-- 顶部查询表单 -->
        <div class="layui-card">
            <div class="layui-card-body">
                <form class="layui-form top-search-from">
                    
                    <div class="layui-form-item">
                        <label class="layui-form-label">设备编号</label>
                        <div class="layui-input-block">
                            <input type="text" name="sn" value="" class="layui-input">
                        </div>
                    </div>
                    
                    <div class="layui-form-item">
                        <label class="layui-form-label">网关ID</label>
                        <div class="layui-input-block">
                            <input type="text" name="gateway_id" value="" class="layui-input">
                        </div>
                    </div>
                    
                    <div class="layui-form-item layui-inline">
                        <label class="layui-form-label"></label>
                        <button class="pear-btn pear-btn-md pear-btn-primary" lay-submit lay-filter="table-query">
                            <i class="layui-icon layui-icon-search"></i>查询
                        </button>
                        <button type="reset" class="pear-btn pear-btn-md" lay-submit lay-filter="table-reset">
                            <i class="layui-icon layui-icon-refresh"></i>重置
                        </button>
                    </div>
                    <div class="toggle-btn">
                        <a class="layui-hide">展开<i class="layui-icon layui-icon-down"></i></a>
                        <a class="layui-hide">收起<i class="layui-icon layui-icon-up"></i></a>
                    </div>
                </form>
            </div>
        </div>
        
        <!-- 数据表格 -->
        <div class="layui-card">
            <div class="layui-card-body">
                <table id="data-table" lay-filter="data-table"></table>
            </div>
        </div>

        <!-- 表格顶部工具栏 -->
        <script type="text/html" id="table-toolbar">
            <button class="pear-btn pear-btn-primary pear-btn-md" lay-event="add" permission="app.admin.device.insert">
                <i class="layui-icon layui-icon-add-1"></i>新增
            </button>
            <button class="pear-btn pear-btn-danger pear-btn-md" lay-event="batchRemove" permission="app.admin.device.delete">
                <i class="layui-icon layui-icon-delete"></i>删除
            </button>
        </script>

        <!-- 表格行工具栏 -->
        <script type="text/html" id="table-bar">
            <button class="pear-btn pear-btn-xs tool-btn" lay-event="edit" permission="app.admin.device.update">编辑</button>
            <button class="pear-btn pear-btn-xs tool-btn" lay-event="remove" permission="app.admin.device.delete">删除</button>
            <button class="pear-btn pear-btn-xs tool-btn" lay-event="viewQuality">水质指标信息</button>
            <button class="pear-btn pear-btn-xs tool-btn" lay-event="viewBindUsers">绑定用户</button>
        </script>

        <script src="/app/admin/component/layui/layui.js?v=2.8.12"></script>
        <script src="/app/admin/component/pear/pear.js"></script>
        <script src="/app/admin/admin/js/permission.js"></script>
        <script src="/app/admin/admin/js/common.js"></script>
        
        <script>

            // 相关常量
            const PRIMARY_KEY = "id";
            const SELECT_API = "/app/admin/device/select";
            const UPDATE_API = "/app/admin/device/update";
            const DELETE_API = "/app/admin/device/delete";
            const INSERT_URL = "/app/admin/device/insert";
            const UPDATE_URL = "/app/admin/device/update";
            
            // 表格渲染
            layui.use(["table", "form", "common", "popup", "util"], function() {
                let table = layui.table;
                let form = layui.form;
                let $ = layui.$;
                let common = layui.common;
                let util = layui.util;
                
				// 表头参数
				let cols = [
					{
						type: "checkbox",
						align: "center"
					},{
						title: "主键",align: "center",
						field: "id",
						hide: true,
					},{
						title: "创建时间",align: "center",
						field: "created_at",
						sort: true,
					},{
						title: "更新时间",align: "center",
						field: "updated_at",
						hide: true,
					},
                    {
						title: "设备名称",align: "center",
						field: "device_name_id",
						templet: function (d) {
							let field = "device_name_id";
							if (typeof d[field] == "undefined") return "";
							let items = [];
							layui.each((d[field] + "").split(","), function (k , v) {
								items.push(apiResults[field][v] || v);
							});
                            // console.log(items);
							return util.escape(items.join(","));
						}
					},
                    {
						title: "设备编号",align: "center",
						field: "sn",
					},{
						title: "网关ID",align: "center",
						field: "gateway_id",
					},
                    {
						title: "膜件号",align: "center",
						field: "mold_number",
					},
                    {
						title: "客户名称",align: "center",
						field: "customer_name",
					},
                    {
						title: "客户手机号",align: "center",
						field: "customer_phone",
					},
                    {
						title: "客户所在省",align: "center",
						field: "customer_province",
					},
                    {
						title: "客户所在市",align: "center",
						field: "customer_city",
					},
                    
                    {
						title: "开关机状态",align: "center",
						field: "status",
						templet: function (d) {
							let field = "status";
							if (typeof d[field] == "undefined") return "";
							let items = [];
							layui.each((d[field] + "").split(","), function (k , v) {
                                if(v > 1){
                                    v = 1;
                                }
								items.push(apiResults[field][v] || v);
							});
							return util.escape(items.join(","));
						}
					},{
						title: "在线状态",align: "center",
						field: "is_online",
						templet: function (d) {
							let field = "is_online";
							if (typeof d[field] == "undefined") return "";
							let items = [];
							layui.each((d[field] + "").split(","), function (k , v) {
								items.push(apiResults[field][v] || v);
							});
							return util.escape(items.join(","));
						}
                    
					 },
                     {
						title: "报警码",align: "center",
						field: "alarm",
					},
                    // {
					// 	title: "余氟",align: "center",
					// 	field: "cl",
					// },{
					// 	title: "PH值",align: "center",
					// 	field: "ph",
					// },{
					// 	title: "水质",align: "center",
					// 	field: "tds",
					// },{
					// 	title: "滤芯寿命",align: "center",
					// 	field: "filter",
					// },{
					// 	title: "累计产水量",align: "center",
					// 	field: "water",
					// },
                    {
						title: "last_send_at",align: "center",
						field: "last_send_at",
						hide: true,
					},{
						title: "操作",
						toolbar: "#table-bar",
						align: "center",
						fixed: "right",
						width: 280,
					}
				];
				
				// 渲染表格
				table.render({
				    elem: "#data-table",
				    url: SELECT_API,
				    page: true,
				    cols: [cols],
				    skin: "line",
				    size: "lg",
				    toolbar: "#table-toolbar",
				    autoSort: false,
				    defaultToolbar: [{
				        title: "刷新",
				        layEvent: "refresh",
				        icon: "layui-icon-refresh",
				    }, "filter", "print", "exports"],
				    done: function () {
				        layer.photos({photos: 'div[lay-id="data-table"]', anim: 5});
				    }
				});
				
				// 获取表格中下拉或树形组件数据
				let apiResults = {};
				apiResults["status"] = ["关机","开机"];
				apiResults["is_online"] = ["离线","在线"];


                // 获取表格中下拉或树形组件数据
				let apis = [];
				apis.push(["device_name_id", "/app/admin/device-name/select?format=select"]);
				apiResults["type"] = {"1":"上门服务"};
				apiResults["device_name_id"] = [];
				let count = apis.length;
				layui.each(apis, function (k, item) {
				    let [field, url] = item;
				    $.ajax({
				        url: url,
				        dateType: "json",
				        success: function (res) {
				            if (res.code) {
				                return layui.popup.failure(res.msg);
				            }
				            function travel(items) {
				                for (let k in items) {
				                    let item = items[k];
                                    console.log(item,item.name);
                                    // console.log(apiResults[field]);
				                    apiResults[field][item.value] = item.name;
				                    if (item.children) {
				                        travel(item.children);
				                    }
				                }
				            }
                            console.log(res.data);
				            travel(res.data);
				        },
				        complete: function () {
				            if (--count === 0) {
				                render();
				            }
				        }
				    });
				});
				if (!count) {
				    render();
				}

                function render()
				{
				    table.render({
				        elem: "#data-table",
				        url: SELECT_API,
				        page: true,
				        cols: [cols],
				        skin: "line",
				        size: "lg",
				        toolbar: "#table-toolbar",
				        autoSort: false,
				        defaultToolbar: [{
				            title: "刷新",
				            layEvent: "refresh",
				            icon: "layui-icon-refresh",
				        }, "filter", "print", "exports"],
				        done: function () {
				            layer.photos({photos: 'div[lay-id="data-table"]', anim: 5});
				        }
				    });
				}

                // 编辑或删除行事件
                table.on("tool(data-table)", function(obj) {
                    if (obj.event === "remove") {
                        remove(obj);
                    } else if (obj.event === "edit") {
                        edit(obj);
                    } else if (obj.event === "viewQuality") {
                        viewQuality(obj.data);
                    } else if (obj.event === "viewBindUsers") {
                        viewBindUsers(obj.data);
                    }
                });

                // 表格顶部工具栏事件
                table.on("toolbar(data-table)", function(obj) {
                    if (obj.event === "add") {
                        add();
                    } else if (obj.event === "refresh") {
                        refreshTable();
                    } else if (obj.event === "batchRemove") {
                        batchRemove(obj);
                    }
                });

                // 表格顶部搜索事件
                form.on("submit(table-query)", function(data) {
                    table.reload("data-table", {
                        page: {
                            curr: 1
                        },
                        where: data.field
                    })
                    return false;
                });
                
                // 表格顶部搜索重置事件
                form.on("submit(table-reset)", function(data) {
                    table.reload("data-table", {
                        where: []
                    })
                });
                
                // 字段允许为空
                form.verify({
                    phone: [/(^$)|^1\d{10}$/, "请输入正确的手机号"],
                    email: [/(^$)|^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/, "邮箱格式不正确"],
                    url: [/(^$)|(^#)|(^http(s*):\/\/[^\s]+\.[^\s]+)/, "链接格式不正确"],
                    number: [/(^$)|^\d+$/,'只能填写数字'],
                    date: [/(^$)|^(\d{4})[-\/](\d{1}|0\d{1}|1[0-2])([-\/](\d{1}|0\d{1}|[1-2][0-9]|3[0-1]))*$/, "日期格式不正确"],
                    identity: [/(^$)|(^\d{15}$)|(^\d{17}(x|X|\d)$)/, "请输入正确的身份证号"]
                });

                // 表格排序事件
                table.on("sort(data-table)", function(obj){
                    table.reload("data-table", {
                        initSort: obj,
                        scrollPos: "fixed",
                        where: {
                            field: obj.field,
                            order: obj.type
                        }
                    });
                });

                // 表格新增数据
                let add = function() {
                    layer.open({
                        type: 2,
                        title: "新增",
                        shade: 0.1,
                        maxmin: true,
                        area: [common.isModile()?"100%":"500px", common.isModile()?"100%":"450px"],
                        content: INSERT_URL
                    });
                }

                // 表格编辑数据
                let edit = function(obj) {
                    let value = obj.data[PRIMARY_KEY];
                    layer.open({
                        type: 2,
                        title: "修改",
                        shade: 0.1,
                        maxmin: true,
                        area: [common.isModile()?"100%":"500px", common.isModile()?"100%":"450px"],
                        content: UPDATE_URL + "?" + PRIMARY_KEY + "=" + value
                    });
                }

                // 删除一行
                let remove = function(obj) {
                    return doRemove(obj.data[PRIMARY_KEY]);
                }

                // 删除多行
                let batchRemove = function(obj) {
                    let checkIds = common.checkField(obj, PRIMARY_KEY);
                    if (checkIds === "") {
                        layui.popup.warning("未选中数据");
                        return false;
                    }
                    doRemove(checkIds.split(","));
                }

                // 执行删除
                let doRemove = function (ids) {
                    let data = {};
                    data[PRIMARY_KEY] = ids;
                    layer.confirm("确定删除?", {
                        icon: 3,
                        title: "提示"
                    }, function(index) {
                        layer.close(index);
                        let loading = layer.load();
                        $.ajax({
                            url: DELETE_API,
                            data: data,
                            dataType: "json",
                            type: "post",
                            success: function(res) {
                                layer.close(loading);
                                if (res.code) {
                                    return layui.popup.failure(res.msg);
                                }
                                return layui.popup.success("操作成功", refreshTable);
                            }
                        })
                    });
                }

                // 刷新表格数据
                window.refreshTable = function() {
                    table.reloadData("data-table", {
                        scrollPos: "fixed",
                        done: function (res, curr) {
                            if (curr > 1 && res.data && !res.data.length) {
                                curr = curr - 1;
                                table.reloadData("data-table", {
                                    page: {
                                        curr: curr
                                    },
                                })
                            }
                        }
                    });
                }

                // 查看水质信息弹窗及自动刷新
                function viewQuality(device) {
                    let layerIndex;
                    let timer;
                    function renderContent(data) {
                        return `
                        <div id="quality-content">
                            <table class="layui-table">
                                <tr><td>余氟</td><td>${data.cl ?? '-'}</td></tr>
                                <tr><td>PH值</td><td>${data.ph ?? '-'}</td></tr>
                                <tr><td>Tds值</td><td>${data.tds ?? '-'}</td></tr>
                                <tr><td>滤芯寿命(次)</td><td>${data.filter ?? '-'}</td></tr>
                                <tr><td>累计产水量(t)</td><td>${data.water ?? '-'}</td></tr>
                            </table>
                        </div>
                        `;
                    }
                    function fetchAndUpdate() {
                        layui.$.ajax({
                            url: '/app/admin/device/quality',
                            type: 'get',
                            data: {id: device.id},
                            success: function(res) {
                                if(res.code === 0 && res.data) {
                                    layui.$('#quality-content').replaceWith(renderContent(res.data));
                                }
                            }
                        });
                    }
                    layerIndex = layer.open({
                        type: 1,
                        title: device.sn +' 水质指标（此为近一分钟内数值的平均值，每10s自动刷新）',
                        area: ['650px', '400px'],
                        content: renderContent(device),
                        end: function() {
                            if(timer) clearInterval(timer);
                        }
                    });
                    // 只刷新非状态和报警码字段
                    timer = setInterval(function() {
                        fetchAndUpdate();
                    }, 10000);
                }

                // 查看绑定用户弹窗
                function viewBindUsers(device) {
                    let layerIndex;
                    let loading = layer.load();
                    layui.$.ajax({
                        url: '/app/admin/device/bind-users',
                        type: 'get',
                        data: {id: device.id},
                        success: function(res) {
                            layer.close(loading);
                            if(res.code === 0 && res.data && res.data.length) {
                                let html = `<div style='padding:16px;'><table class='layui-table'>
                                    <thead><tr><th>用户名</th><th>手机号</th></tr></thead><tbody>`;
                                res.data.forEach(function(user) {
                                    html += `<tr><td>${user.nickname ?? '-'}</td><td>${user.phone ?? '-'}</td></tr>`;
                                });
                                html += '</tbody></table></div>';
                                layerIndex = layer.open({
                                    type: 1,
                                    title: device.sn + ' 绑定用户',
                                    area: ['400px', 'auto'],
                                    content: html
                                });
                            } else {
                                layer.msg('暂无绑定用户');
                            }
                        },
                        error: function() {
                            layer.close(loading);
                            layer.msg('请求失败');
                        }
                    });
                }
            })

        </script>
    </body>
</html>
